package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Reference
    private SpuService spuService;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${pagePath}")
    private String pagePath;

    @Reference
    private CategoryService categoryService;

    @GetMapping("/item")
    public String itemPage(String spuId){

        return "item";
    }

    @GetMapping("/createPage")
    public void createPage(String spuId){

       //1:商品基本信息
        Goods goods = spuService.findGoodsById(spuId);

        //spu
        Spu spu = goods.getSpu();
        //sku
        List<Sku> skuList = goods.getSkuList();

        //分类信息
        List<String> categoryList=new ArrayList<>();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());


        //先组装 url
        Map urlMap =new HashMap();
        for(Sku sku :skuList){
            //url
            String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
            urlMap.put(specJson,sku.getId()+".html");
        }


        //循环生成sku页面
        for(Sku sku :skuList){

            //2：thymeleaf 静态页面封装数据
            Context context=new Context();
            Map<String,Object> datamap =new HashMap<String,Object>();
            datamap.put("spu",spu);
            datamap.put("sku",sku);
            datamap.put("categoryList",categoryList);
            datamap.put("spuImages",spu.getImages().split(","));
            datamap.put("skuImages",sku.getImages().split(","));

            //规格列表
            Map paraItems = JSON.parseObject(spu.getParaItems());
            datamap.put("paraItems",paraItems);

            //参数列表
            Map specItems = JSON.parseObject(sku.getSpec());
            datamap.put("specItems",specItems);



            //规格面板
            Map<String,List> specMap =  (Map)JSON.parseObject(spu.getSpecItems());
            for(String key :specMap.keySet()){
                List<Map> mapList=new ArrayList<>();

                List<String> list = specMap.get(key);
                for(String value : list){
                    Map map =new HashMap();
                    map.put("option",value);

                    if(specItems.get(key).equals(value)){
                        map.put("checked",true);
                    }else{
                        map.put("checked",false);
                    }

                    Map<String,String>  spec= (Map)JSON.parseObject(sku.getSpec()) ;//当前的Sku
                    //url
                    spec.put(key,value);
                    String specStr = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                    map.put("url",urlMap.get(specStr));
                    mapList.add(map);
                }
                specMap.put(key,mapList);
            }
            datamap.put("specMap",specMap);
            
            
            



            context.setVariables(datamap);

            //3: 生成页面
            try {
                File dir =new File(pagePath);
                if( !dir.exists()){
                    dir.mkdirs();
                }
                File dest= new File(dir, sku.getId()+".html" );
                PrintWriter writer=new PrintWriter( dest,"UTF-8");
                templateEngine.process("item",context,writer);
                System.out.println("生成页面："+sku.getId()+".html");


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }


        }


    }

}
